package com.example.program.controller;
//过滤器or 拦截器
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.example.program.pojo.Result;
import com.example.program.utils.JWT;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class TFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
       String url=request.getRequestURI();
///2.判断请求url中是否包含login，如果包含，说明是登录操作，放行
if(url.contains("/login"))
{
    //放行
    filterChain.doFilter(servletRequest,servletResponse);
    return;
}
//3.获取令牌
        String token=request.getHeader("token");
//4.判断令牌是否存在
        if(StringUtils.isEmpty(token))
        {
            Result error=Result.error("NOT_LOGIN");
            String not= JSONObject.toJSONString(error);
            response.getWriter().write(not);
            return;
        }
//解析TOKEN
        try{
            JWT.parseJWT(token);
        }catch (Exception e)
        {
            Result error=Result.error("NOT_LOGIN");
            String not= JSONObject.toJSONString(error);
            response.getWriter().write(not);
            return;
        }


        filterChain.doFilter(servletRequest, servletResponse);

    }


}
